package dk.sensobyg.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import dk.sensobyg.base.Controller;
import dk.sensobyg.base.SensorData;
import dk.sensobyg.communication.Serializer;
import dk.sensobyg.communication.UnSerializer;

public class BaseStationServer implements Runnable {
	Controller controller;
	
	public BaseStationServer(Controller controller) {
		this.controller = controller;
	}
	
	class Service implements Runnable {
		private Socket client;
		
		public Service(Socket client) {
			this.client = client;
		}
		
		public void run() {
			System.out.println("Service running...");
			try {
				OutputStream output = client.getOutputStream();
				Serializer serializer = new Serializer(output);
				InputStream input = client.getInputStream();
				UnSerializer unserializer = new UnSerializer(input);
				
				String command = unserializer.readString();
				System.out.println("command " + command);
				if (command.equals("latest")) {
					int sensor_id = unserializer.readInt();
					System.out.println("id " + sensor_id);
					SensorData data = controller.getLatest(sensor_id);
					if (data != null) {
						serializer.writeString("data");
						serializer.writeInt((int) data.getTimestamp());
						serializer.writeInt((int) data.getData());
					} else {
						serializer.writeString("null");
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public void run() {
		try {
			System.out.println("Server running...");
			ServerSocket server = new ServerSocket(8800);
			while (true) {
				Socket client = server.accept();
				Thread thread = new Thread(new Service(client));
				thread.start();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
